package com.dhcc.controller;

import com.dhcc.api.R;
import com.dhcc.entity.ClientUser;
import com.dhcc.entity.SysUserResource;
import com.dhcc.httpApiService.IdGeneratorService;
import com.dhcc.service.ClientUserService;
import com.dhcc.service.InstitutionRoleDepartmentPositionService;
import com.dhcc.service.SysUserResourceService;
import com.dhcc.utils.AuthUtil;
import com.dhcc.utils.ResourceTreeBuilder;
import com.dhcc.vo.SysClientResourceListTree;
import com.dhcc.vo.SysUserResourceVO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.IllegalFormatCodePointException;
import java.util.List;

@RestController
@RequestMapping("/userSystem/resource")
public class SysUserResourceController {
    @Resource
    private SysUserResourceService sysUserResourceService;
    @Resource
    private ClientUserService clientUserService;
    @Resource
    private IdGeneratorService idGeneratorService;
    @Resource
    private InstitutionRoleDepartmentPositionService institutionRoleDepartmentPositionService;
    /**
     * 查询当前机构下的所有资源列表
     */
    @GetMapping("/selectResourceList")
    public R<List<SysClientResourceListTree>> selectResourceListTree(String institutionId, String institutionRoleId, String departmentId, String positionId){
        List<SysUserResource> sysUserResourceList= sysUserResourceService.selectResourceList(institutionId,institutionRoleId,departmentId,positionId);
        List<SysClientResourceListTree> sysClientResourceListTrees = ResourceTreeBuilder.buildResourceTree(sysUserResourceList, null);
        return R.data(sysClientResourceListTrees);
    }
    /**
     * 查询当前机构下的所有资源列表
     */
    @GetMapping("/selectParentResourceList")
    public R<List<SysClientResourceListTree>> selectResourceList(String institutionId, String institutionRoleId, String departmentId, String positionId){
        List<SysUserResource> sysUserResourceList= sysUserResourceService.selectResourceList(institutionId,institutionRoleId,departmentId,positionId);
        List<SysUserResource> sysUserResources=new ArrayList<>();
        for (SysUserResource sysUserResource : sysUserResourceList) {
            if (!sysUserResource.getResourceType().equals("button")){
                sysUserResources.add(sysUserResource);
            }
        }
        List<SysClientResourceListTree> sysClientResourceListTrees = ResourceTreeBuilder.buildResourceTree(sysUserResources, null);
        return R.data(sysClientResourceListTrees);
    }
    /**
     * 资源新增
     */
    @PostMapping("/addResource")
    @Transactional
    public R addResource(@RequestBody SysUserResourceVO sysUserResourceVO){
        Long aLong = idGeneratorService.nextId();
        sysUserResourceVO.setResourceId(aLong.toString());
        String userId = AuthUtil.getUserId();
        ClientUser user = clientUserService.getUserById(userId);
        sysUserResourceVO.setCreateUser(user.getName());
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 定义日期时间格式化器，格式化为 "yyyy-MM-dd HH:mm:ss"
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化当前时间
        String formattedDateTime = now.format(formatter);
        sysUserResourceVO.setCreateTime(formattedDateTime);
        SysUserResource sysUserResource=new SysUserResource();
        BeanUtils.copyProperties(sysUserResourceVO,sysUserResource);
        Integer addResult= sysUserResourceService.addResource(sysUserResource);
        if (addResult!=1){
            throw new RuntimeException("数据库资源添加失败");
        }
        //添加关联数据
        Integer integer = institutionRoleDepartmentPositionService.addData(sysUserResourceVO.getInstitutionId(), sysUserResourceVO.getInstitutionRoleId(), sysUserResourceVO.getDepartmentId(), sysUserResourceVO.getPositionId(), sysUserResourceVO.getResourceId());
        if (integer!=1){
            return R.fail("关联表数据添加失败");
        }
        return R.success();
    }
    /**
     * 查询资源详情
     */
    @GetMapping("/getResourceInfo")
    public R getResourceInfo(String resourceId){
        return R.data(sysUserResourceService.getResourceById(resourceId));
    }
    /**
     * 资源修改
     */
    @PostMapping("/updateResource")
    public R updateResource(@RequestBody SysUserResourceVO sysUserResourceVO){
        String userId = AuthUtil.getUserId();
        ClientUser user = clientUserService.getUserById(userId);
        sysUserResourceVO.setUpdateUser(user.getName());
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 定义日期时间格式化器，格式化为 "yyyy-MM-dd HH:mm:ss"
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化当前时间
        String formattedDateTime = now.format(formatter);
        sysUserResourceVO.setUpdateTime(formattedDateTime);
        SysUserResource sysUserResource=new SysUserResource();
        BeanUtils.copyProperties(sysUserResourceVO,sysUserResource);
        Integer updateResult= sysUserResourceService.updateResource(sysUserResource);
        if (updateResult!=1){
            throw new RuntimeException("资源更新失败");
        }
        return R.success();
    }
    /**
     * 资源删除（删除关联表的关联数据）
     */
    @GetMapping("/deleteResource")
    public R deleteResource(String institutionId,String institutionRoleId, String departmentId, String positionId, String resourceId){
        List<SysUserResource> resourceList = sysUserResourceService.getResourceListByParentId(resourceId);
        if (resourceList.size()!=0){
            return R.fail("该资源下还存在其他子资源，请先删除子资源");
        }
        Integer deleteResult=institutionRoleDepartmentPositionService.deleteData(institutionId,institutionRoleId,departmentId,positionId,resourceId);
        if (deleteResult!=1){
            throw new RuntimeException("删除失败");
        }
        return R.success();
    }


}
